/**
 * 21point
 *
 * outlook@China software studio
 * Copyright (c) 2008-2010. All Rights Reserved.
 * http://www.outlook.com
 */

package org.outlook.game.arithmetic;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

/**
 * function:
 * @author Watson email: watson.wu@hotmail.com
 * @date 2011
 */
public class PokerParser {

	public static final int POKER_WIDTH = 220;
	public static final int POKER_HEIGHT = 310;

	public static Poker parser(URL path, String fileName) {
		if(path == null && null == fileName) return null;
		final URL filePath = PokerParser.getResourceInRoot("images/"+fileName);
		final ImageIcon icon = new ImageIcon(getImage(filePath));

		final JLabel image = new JLabel();
		String fileNameWithoutSubffix = fileName.substring(0, fileName.indexOf("."));
		final String desc = getDescription(fileNameWithoutSubffix);
		image.setToolTipText(desc);
		image.setIcon(icon);
		image.setPreferredSize(new Dimension(POKER_WIDTH, POKER_HEIGHT));
		image.setHorizontalAlignment(SwingConstants.CENTER);
		return new Poker(getNum(fileNameWithoutSubffix), getSuit(fileNameWithoutSubffix), desc, image);
	}
	
	private static int getSuit(String fileName) {
//		switch(fileName.charAt(fileName.length()-1)) {
//		case 'a':
//			return 1;
//		case 'b':
//			return 2;
//		case 'c':
//			return 3;
//		case 'd':
//			return 4;
//		}
		return fileName.charAt(fileName.length()-1)-96;
	}

	private static int getNum(String fileName) {
		if(null == fileName && "".equals(fileName)) return 0;
		if(fileName.startsWith("11") || fileName.startsWith("12") || fileName.startsWith("13"))
			return 10;
		else
			return Integer.parseInt(fileName.substring(0, fileName.length()-1));
	}

	private static String getDescription(String fileName) {
		if(null == fileName && "".equals(fileName)) return null;
		if(fileName.startsWith("11"))
			return "J";
		else if(fileName.startsWith("12"))
			return "Q";
		else if(fileName.startsWith("13"))
			return "K";
		else if(fileName.startsWith("1") && !fileName.startsWith("10"))
			return "A";
		return fileName.substring(0, fileName.length()-1);
	}

	public static Image getImage(URL filePath) {
		return Toolkit.getDefaultToolkit().getImage(filePath);
	}

	public static URL getResourceInRoot(String path) {
		final URL url = Main.class.getClassLoader().getResource(path);
		return url;
	}	

}
